/* UDP 服务器端代码 server.c */
#include "udp_service.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "frame_util.h"

#define BUFFER_SIZE 1024
#define PORT 8888

void *udp_worker(void *param) {
    int server_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    uint8_t buffer[BUFFER_SIZE];

    // 创建UDP套接字
    if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定套接字
    if (bind(server_socket, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(server_socket);
        return;
    }

    printf("Server started on port %d...\n", PORT);

    while(1) {
        // 接收客户端消息
        ssize_t recv_len = recvfrom(server_socket, buffer, BUFFER_SIZE, 0,
                                   (struct sockaddr *)&client_addr, &client_len);
        if (recv_len < 0) {
            perror("recvfrom failed");
            continue;
        }
        printf("UDP Service 接收到的原始数据: ");
        int i = 0;
        
        while(buffer != NULL && i < recv_len)
        {
            printf("%02X ", *(buffer + i));
            i++;
        }
        printf("\n");

        if(buffer[0]==0xA5 && buffer[recv_len-1] == 0xA3) {
            LoraData d;
            uint8_t *res = NULL;
            uint16_t res_len = decode_frame(buffer, recv_len, &res);
            if(res_len > 0){
                LoraData d;
                parse_frame(res, res_len, &d);
                if(d.len > 0){
                    data_parse(d);
                }       
                free(res);
            }
        }
        // 发送响应
        const char *response = "Message received by server";
        if (sendto(server_socket, response, strlen(response), 0,
                  (const struct sockaddr *)&client_addr, client_len) < 0) {
            perror("sendto failed");
        }
    }

    close(server_socket);
    return 0;
}

void udp_worker_start(void)
{
    pthread_t pid;
    pthread_create(&pid, NULL, (void *)udp_worker, NULL);
}
